package com.lhq.tag_tales.interceptor;

import com.lhq.tag_tales.common.ErrorCodeEnum;
import com.lhq.tag_tales.exception.BusinessException;
import com.lhq.tag_tales.model.domain.User;
import com.lhq.tag_tales.utils.UserUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.lhq.tag_tales.constant.UserConstant.USER_LOGIN_STATE;

public class UserContextInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 在请求开始时设置当前用户
        User user = (User) request.getSession().getAttribute(USER_LOGIN_STATE);
        if (user == null) {
            throw new BusinessException(ErrorCodeEnum.NO_LOGIN, "未登录");
        }
        Integer isValid = user.getIsValid();
        if (isValid == 0) {
            throw new BusinessException(ErrorCodeEnum.NO_LOGIN, "账号还未通过验证");
        }
        UserUtils.setCurrentUser(user);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 处理请求后的逻辑
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 在请求结束时清除当前用户
        UserUtils.removeCurrentUser();
    }
}
